package com.aefottt.struggle_star.view;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateInterpolator;

import androidx.annotation.Nullable;
import androidx.interpolator.view.animation.FastOutSlowInInterpolator;

public class RippleView extends View {
    public static final int RIPPLE_START = 0;
    public static final int RIPPLE_END = 1;

    private static final int rippleColor = Color.parseColor("#19375E");

    private float radius;
    private float startX, startY;
    private final Paint paint = new Paint();
    private OnRippleListener onRippleListener;
    public RippleView(Context context) {
        super(context);
    }

    public RippleView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        paint.setColor(rippleColor);
        paint.setAntiAlias(true); // 抗锯齿
        paint.setDither(true); // 防抖动
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(startX, startY, radius, paint);
    }

    public void startRippleAnim(float positionX, float positionY){
        onRippleListener.onRipple(RIPPLE_START);
        this.startX = positionX;
        this.startY = positionY;
        // 计算总的圆半径
        float side = (float) Math.sqrt(Math.pow(getWidth(), 2) + Math.pow(getHeight(), 2)) + 100;
        ObjectAnimator animator = ObjectAnimator.ofFloat(this, "radius", 0, side);
        animator.setDuration(800);
        animator.setInterpolator(new FastOutSlowInInterpolator());
        animator.start();
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                onRippleListener.onRipple(RIPPLE_END);
            }
        });
    }

    public void setRadius(float radius) {
        this.radius = radius;
        invalidate();
    }

    public float getRadius() {
        return radius;
    }

    public void setOnRippleListener(OnRippleListener onRippleListener) {
        this.onRippleListener = onRippleListener;
    }

    public interface OnRippleListener{
        void onRipple(int state);
    }
}
